package com.szs.aop;



import com.szs.mapper.OperateLogMapper;
import com.szs.mapper.OperateLogMapper;
import com.szs.pojo.OperateLog;
import com.szs.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    // 定义切入点，匹配 com.szs.controller 包下的所有方法
    @Around("@annotation(com.szs.anno.Log)")
    public Object recordOperateLog(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取操作人 ID，这里假设从当前会话中获取，实际应用中需要根据具体情况修改


        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 记录结束时间
        long endTime = System.currentTimeMillis();

        // 计算方法执行时长
        long costTime = endTime - startTime;

        // 创建操作日志对象
        OperateLog operateLog = new OperateLog();

        operateLog.setOperateEmpId(getCurrentOperateEmpId());
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result != null ? result.toString() : "void");
        operateLog.setCostTime(costTime);

        // 保存操作日志

        log.info("记录操作日志：{}", operateLog);
        operateLogMapper.insert(operateLog);

        return result;
    }
    private Integer getCurrentOperateEmpId() {
        return CurrentHolder.getCurrentId();
    }
}    